<?php 
/**
 *  
 */
date_default_timezone_set("Asia/Shanghai");

set_time_limit(0);

if (isset ( $_SERVER ['REQUEST_URI'] )) {
    die ( 'error' );
}
if (! defined ( 'API_ROOT_PATH' )) {
    define ( 'API_ROOT_PATH', dirname ( __FILE__ ) );
}

if (!function_exists("pcntl_fork")) {  

    die();  
}

require_once (API_ROOT_PATH . '/../inc/Config.php');
require_once (API_ROOT_PATH . '/../inc/dblink.php');
require_once (API_ROOT_PATH . '/../inc/Mysql.php');

$db = new Mysql ( MYSQLDB, MYSQLDB_USER, MYSQLDB_PWD, MYSQLDB_DATABASE );

$sql = "select max(order_id) as max_order_id from au_order";

$maxOrderId = $db ->fetchOne($sql);

$db->close();

unset($db);  

$db = null;

$cmdArr = array();  

//进程数量
$workers = 20;

$cmdArr = [];

$manyInterval = interval($maxOrderId['max_order_id'],$workers);

for ($i=0; $i < $workers ; $i++) { 

    $cmdArr[] = [

        'path' => __DIR__ . '/run_order_fee.php',

        'start' =>$manyInterval[$i]['start_num'],

        'end' =>$manyInterval[$i]['end_num']
    ];  
}

echo "parent start, pid ", getmypid(), "\n" ;

pcntl_signal(SIGCHLD, SIG_IGN); 

foreach ($cmdArr as $key => $cmd) {  

    $pid = pcntl_fork();  

    if ($pid == -1) {  

        die();  

    } else if ($pid > 0) {  
        
        pcntl_wait($status,WNOHANG); 

    } else if ($pid == 0) {  

        echo "child start, pid ", getmypid(), "\n" ;

        $path   = $cmd["path"];   

        $start = $cmd['start'] ;  

        $end = $cmd['end'] ;  

        exec("/usr/bin/php {$path} {$start} {$end} >> order_fee_log".$key.".txt")."\n";  

        exit(0) ;  
    }  
}


function interval($maxId,$workers)
{
    $arr = [];

    $baseNun = ceil($maxId/$workers);

    for ($i=0; $i < $workers; $i++) {

        if ($i == 0) {

            $arr[0]['start_num'] = 1;

            $arr[0]['end_num'] = 1+$baseNun;

        }else{

            $arr[$i]['start_num'] = $arr[$i-1]['end_num'] + 1;

            if ($i == $workers -1) {

                $arr[$i]['end_num'] = $maxId;

            }else{

                $arr[$i]['end_num'] = $arr[$i]['start_num']+$baseNun;

            }

        }
        
    }

    return $arr;
}